<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2014 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Tuolaji <479923197@qq.com>
// +----------------------------------------------------------------------
namespace Portal\Controller;

use Common\Controller\AdminbaseController;

class AdminHonorController extends AdminbaseController {

    protected $model;
    protected $terms_model;

    function _initialize() {
        parent::_initialize();
        $this->model = D("Portal/Honor");
    }

    public function index(){
        $this->_lists(array("status"=>array('eq',1)));
        $this->display();
    }

    public function add(){
        $this->display();
    }

    public function add_post(){
        if (IS_POST) {
            if(!empty($_POST['photos_alt']) && !empty($_POST['photos_url'])){
                foreach ($_POST['photos_url'] as $key=>$url){
                    $photourl=sp_asset_relative_url($url);
                    $_POST['smeta']['photo'][]=array("url"=>$photourl,"alt"=>$_POST['photos_alt'][$key]);
                }
            }
            $_POST['smeta']['images'] = sp_asset_relative_url($_POST['smeta']['thumb']);
            $_POST['post']['updated_time']=date("Y-m-d H:i:s",time());
            $_POST['post']['author']=get_current_admin_id();
            $article=I("post.post");
            $article['smeta']=json_encode($_POST['smeta']);
            $article['content']=htmlspecialchars_decode($article['content']);
            $result=$this->model->add($article);
            if ($result) {
                $this->success("添加成功！");
            } else {
                $this->error("添加失败！");
            }

        }
    }

    public function edit(){
        $id=  intval(I("get.id"));
        $post=$this->model->where("id=$id")->find();
        $this->assign("post",$post);
        $this->assign("smeta",json_decode($post['smeta'],true));
        $this->display();
    }
    //routes规则
    function updateUrlRule(){
        $list = $this->model->where('status =1')->order(array("id"=>"asc"))->select();
        if(!empty($list)){
            $urlRule = '';
            foreach ($list as $key=>$item){
                if(!empty($item['url_rule'])){
                    $urlRule .= "	'".str_replace('.html','',$item['url_rule'])."' =>'".'Case/detail?id='.$item['id']."',\r\n";
                    $data['url_rule'] = $item['url_rule'];
                }else{
                    $urlRule .= "	'case/".$item['id']."' =>'".'Case/detail?id='.$item['id']."',\r\n";
                    $data['url_rule'] = 'case/'.$item['id'].'.html';
                }
                $data['id'] = $item['id'];
                $this->model->save($data);
            }
            if(!empty($urlRule)){
                $content = <<<EOT
<?php
return array(

EOT;
                $content .= $urlRule.");";
                $filename = SITE_PATH.'/data/conf/case_route.php';
                file_put_contents($filename, $content);
            }
        }
    }
    public function edit_post(){
        if (IS_POST) {
            $id=intval($_POST['post']['id']);

            if(!empty($_POST['photos_alt']) && !empty($_POST['photos_url'])){
                foreach ($_POST['photos_url'] as $key=>$url){
                    $photourl=sp_asset_relative_url($url);
                    $_POST['smeta']['photo'][]=array("url"=>$photourl,"alt"=>$_POST['photos_alt'][$key]);
                }
            }
            $_POST['smeta']['thumb'] = sp_asset_relative_url($_POST['smeta']['thumb']);
            $_POST['post']['updated_time']=date("Y-m-d H:i:s",time());
            $article=I("post.post");
            $article['smeta']=json_encode($_POST['smeta']);
            $article['cid']=intval($_POST['term']);
            $article['content']=htmlspecialchars_decode($article['content']);
            $result=$this->model->save($article);
            if ($result!==false) {
                $this->success("保存成功！");
            } else {
                $this->error("保存失败！");
            }
        }
    }

    private function _lists($where=array()){
        $start_time=I('request.start_time');
        if(!empty($start_time)){
            $where['created_time']=array(
                array('EGT',$start_time)
            );
        }

        $end_time=I('request.end_time');
        if(!empty($end_time)){
            if(empty($where['created_time'])){
                $where['created_time']=array();
            }
            array_push($where['created_time'], array('ELT',$end_time));
        }

        $keyword=I('request.keyword');
        if(!empty($keyword)){
            $where['title']=array('like',"%$keyword%");
        }

        $this->model
            ->where($where);
        $count=$this->model->count();

        $page = $this->page($count, 20);

        $this->model
            ->where($where)
            ->limit($page->firstRow , $page->listRows)
            ->order("displayorder desc,created_time DESC");
        $list =$this->model->select();

        $this->assign("page", $page->show('Admin'));
        $this->assign("formget",array_merge($_GET,$_POST));
        $this->assign("list",$list);
    }

    private function _getTree(){
        $term_id=empty($_REQUEST['term'])?0:intval($_REQUEST['term']);
        $result = $this->terms_model->where("taxonomy = 'Honor'")->order(array("listorder"=>"asc"))->select();

        $tree = new \Tree();
        $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
        foreach ($result as $r) {
            $r['str_manage'] = '<a href="' . U("AdminTerm/add", array("parent" => $r['term_id'])) . '">添加子类</a> | <a href="' . U("AdminTerm/edit", array("id" => $r['term_id'])) . '">修改</a> | <a class="js-ajax-delete" href="' . U("AdminTerm/delete", array("id" => $r['term_id'])) . '">删除</a> ';
            $r['visit'] = "<a href='#'>访问</a>";
            $r['taxonomys'] = $this->taxonomys[$r['taxonomy']];
            $r['id']=$r['term_id'];
            $r['parentid']=$r['parent'];
            $r['selected']=$term_id==$r['term_id']?"selected":"";
            $array[] = $r;
        }

        $tree->init($array);
        $str="<option value='\$id' \$selected>\$spacer\$name</option>";
        $taxonomys = $tree->get_tree(0, $str);
        $this->assign("taxonomys", $taxonomys);
    }

    private function _getTermTree($term=array()){
        $result = $this->terms_model->where("taxonomy = 'Honor'")->order(array("listorder"=>"asc"))->select();

        $tree = new \Tree();
        $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
        foreach ($result as $r) {
            $r['str_manage'] = '<a href="' . U("AdminTerm/add", array("parent" => $r['term_id'])) . '">添加子类</a> | <a href="' . U("AdminTerm/edit", array("id" => $r['term_id'])) . '">修改</a> | <a class="js-ajax-delete" href="' . U("AdminTerm/delete", array("id" => $r['term_id'])) . '">删除</a> ';
            $r['visit'] = "<a href='#'>访问</a>";
            $r['taxonomys'] = $this->taxonomys[$r['taxonomy']];
            $r['id']=$r['term_id'];
            $r['parentid']=$r['parent'];
            $r['selected']=$r['term_id'] == $term['cid']?"selected":"";
            $r['checked'] =$r['term_id'] == $term['cid']?"checked":"";
            $array[] = $r;
        }

        $tree->init($array);
        $str="<option value='\$id' \$selected>\$spacer\$name</option>";
        $taxonomys = $tree->get_tree(0, $str);
        $this->assign("taxonomys", $taxonomys);
    }

    public function delete(){
        if(isset($_GET['id'])){
            $id = I("get.id",0,'intval');
            if ($this->model->where(array('id'=>$id))->delete() !==false) {
                $this->updateUrlRule();
                $this->success("删除成功！");
            } else {
                $this->error("删除失败！");
            }
        }

        if(isset($_POST['ids'])){
            $ids = I('post.ids/a');

            if ($this->model->where(array('id'=>array('in',$ids)))->delete()!==false) {
                $this->updateUrlRule();
                $this->success("删除成功！");
            } else {
                $this->error("删除失败！");
            }
        }
    }

    function recommend(){
        if(isset($_POST['ids']) && $_GET["recommend"]){
            $ids = I('post.ids/a');

            if ( $this->model->where(array('id'=>array('in',$ids)))->save(array('recommended'=>1))!==false) {
                $this->success("推荐成功！");
            } else {
                $this->error("推荐失败！");
            }
        }
        if(isset($_POST['ids']) && $_GET["unrecommend"]){
            $ids = I('post.ids/a');

            if ( $this->model->where(array('id'=>array('in',$ids)))->save(array('recommended'=>0))!==false) {
                $this->success("取消推荐成功！");
            } else {
                $this->error("取消推荐失败！");
            }
        }
    }

    function recyclebin(){
        $this->_lists(array('status'=>array('eq',3)));
        $this->_getTree();
        $this->display();
    }

    function clean(){
        if(isset($_POST['ids'])){
            $ids = I('post.ids/a');
            $ids = array_map('intval', $ids);
            $status=$this->model->where(array("id"=>array('in',$ids),'status'=>3))->delete();

            if ($status!==false) {
                $this->success("删除成功！");
            } else {
                $this->error("删除失败！");
            }
        }else{
            if(isset($_GET['id'])){
                $id = I("get.id",0,'intval');
                $status=$this->model->where(array("id"=>$id,'status'=>3))->delete();

                if ($status!==false) {
                    $this->success("删除成功！");
                } else {
                    $this->error("删除失败！");
                }
            }
        }
    }

    function restore(){
        if(isset($_GET['id'])){
            $id = I("get.id",0,'intval');
            if ($this->model->where(array("id"=>$id,'status'=>3))->save(array("status"=>"1"))) {
                $this->success("还原成功！");
            } else {
                $this->error("还原失败！");
            }
        }
    }

    public function listorders() {
        $status = $this->_listorders($this->model);
        if ($status) {
            $this->success("排序更新成功！");
        } else {
            $this->error("排序更新失败！");
        }
    }

    public function _listorders() {
        $ids = $_POST['listorders'];
        foreach ($ids as $key => $r) {
            $data['displayorder'] = $r;
            $this->model->where(array('id' => $key))->save($data);
        }
        return true;
    }

}